const { DataTypes } = require('sequelize')

module.exports = (sequelize) => {
  const MemberLevel = sequelize.define('MemberLevel', {
    id: {
      type: DataTypes.INTEGER,
      primaryKey: true,
      autoIncrement: true
    },
    name: {
      type: DataTypes.STRING(50),
      allowNull: false,
      comment: '会员等级名称'
    },
    level: {
      type: DataTypes.INTEGER,
      allowNull: false,
      unique: true,
      comment: '等级值'
    },
    icon: {
      type: DataTypes.STRING(255),
      allowNull: true,
      comment: '等级图标'
    },
    description: {
      type: DataTypes.STRING(500),
      allowNull: true,
      comment: '等级描述'
    },
    points_required: {
      type: DataTypes.INTEGER,
      allowNull: false,
      defaultValue: 0,
      comment: '所需积分'
    },
    discount_rate: {
      type: DataTypes.DECIMAL(5, 2),
      allowNull: false,
      defaultValue: 100.00,
      comment: '折扣率(百分比)'
    },
    points_rate: {
      type: DataTypes.DECIMAL(5, 2),
      allowNull: false,
      defaultValue: 1.00,
      comment: '积分倍率'
    },
    benefits: {
      type: DataTypes.JSON,
      allowNull: true,
      comment: '会员权益'
    },
    status: {
      type: DataTypes.TINYINT,
      allowNull: false,
      defaultValue: 1,
      comment: '状态: 0-禁用, 1-启用'
    },
    created_at: {
      type: DataTypes.DATE,
      allowNull: false,
      defaultValue: DataTypes.NOW,
      comment: '创建时间'
    },
    updated_at: {
      type: DataTypes.DATE,
      allowNull: false,
      defaultValue: DataTypes.NOW,
      comment: '更新时间'
    }
  }, {
    tableName: 'member_levels',
    timestamps: true,
    createdAt: 'created_at',
    updatedAt: 'updated_at',
    indexes: [
      {
        name: 'idx_level',
        fields: ['level']
      },
      {
        name: 'idx_status',
        fields: ['status']
      }
    ]
  })

  MemberLevel.associate = (models) => {
    MemberLevel.hasMany(models.MemberUpgrade, {
      foreignKey: 'level_id',
      as: 'upgrades'
    })
  }

  return MemberLevel
}